﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using O3SqlFileExecuter;
using System.Configuration;
using System.Data.SqlClient;

namespace SqlFileExecuterTester
{
    public partial class _Default : System.Web.UI.Page
    {
        string UploadedFilepath;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (UploadFile())
            {
                SqlFileExecuter sfe = new SqlFileExecuter();
                SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["GTSM"].ConnectionString);

                sfe.FileUrl = Server.MapPath(UploadedFilepath);
                sfe.DestinationConnection = sqlcon;
                sfe.CommandTimeOut = 600;
                lblError.Text=sfe.Execute();
            }

        }
        private bool UploadFile()
        {
            if (FileUploadControl.HasFile)
            {
                try
                {
                    string[] AllowedContentTypes = new string[7] { "application/pdf", "application/vnd.ms-excel", "application/msword",
                                                               "application/vnd.ms-powerpoint", "application/zip", "image/jpeg",
                                                               "text/plain"};

                    if (((IList<string>)AllowedContentTypes).Contains(FileUploadControl.PostedFile.ContentType))
                    {
                        if (FileUploadControl.PostedFile.ContentLength < 2048000)
                        {
                            string filename = Path.GetFileName(FileUploadControl.FileName);
                            FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
                            UploadedFilepath = "~/" + filename;
                            return true;
                        }
                        else
                        {
                            lblError.Text = "FileSizeExceedsAllowedLimit";
                            return false;
                        }
                    }
                    else
                    {
                        lblError.Text = "FileExtensionNotAllowed";
                        return false;
                    }

                }
                catch (Exception ex)
                {
                    lblError.Text = "FileUploadError" + " Ex: " + ex.Message;
                    return false;
                }
            }
            else
            {
                return true;
            }
        }
    }
}
